package com.datviet.controller;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.datviet.domain.UserRegisterDto;
import com.datviet.service.user.IUserRegisterService;
import com.datviet.validator.UserRegisterValidator;

@Controller
@RequestMapping(value = { "/us-register" })
public class UserRegisterController {

	@Autowired
	private IUserRegisterService userRegisterService;

	@Autowired
	private UserRegisterValidator userRegisterValidator;

	@InitBinder()
	private void initBinder(WebDataBinder binder) {
		binder.setValidator(this.userRegisterValidator);
	}

	@RequestMapping(value = { "/register" }, method = RequestMethod.GET)
	public String registerPage(Model model) {
		UserRegisterDto userRegister = new UserRegisterDto();
		model.addAttribute("userRegister", userRegister);

		return "public.register";
	}

	@RequestMapping(value = { "/register" }, method = RequestMethod.POST)
	public String register(@ModelAttribute("userRegister") @Valid UserRegisterDto userRegister,
			BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {			
			return "public.register";
		} else {
			userRegisterService.registerUser(userRegister);
			return "redirect:/app/usr";
		}
	}
}
